﻿using OfficeOpenXml;
using Prism.Ioc;
using SanmaoTools.Common.Untils;
using SanmaoTools.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.Eventing.Reader;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Tryit.ViewModels;
using Path = System.IO.Path;

namespace Tryit.Views
{
    /// <summary>
    /// TPAutoUpload.xaml 的交互逻辑
    /// </summary>
    public partial class TPAutoUpload : Page
    {


        public TPAutoUpload()
        {
            InitializeComponent();
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;

            // 添加按钮点击事件
            uploadButton.MouseLeftButtonDown += UploadButton_Click;
            Loaded += TPAutoUpload_Loaded;



        }

        private void TPAutoUpload_Loaded(object sender, RoutedEventArgs e)
        {
            if (DataContext is TPAutoUploadViewModel viewModel)
            {
                viewModel.RegisterGlobalHotKey();
            }
        }
        // 定义 Windows API
        [DllImport("mpr.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int WNetGetConnection(
            [MarshalAs(UnmanagedType.LPTStr)] string localName,
            [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
            ref int length);

        /// <summary>
        /// 获取所有网络映射驱动器的 UNC 路径
        /// </summary>
        public static void ListMappedDrives()
        {
            DriveInfo[] drives = DriveInfo.GetDrives();
            List<string> mappedDrives = new List<string>();
            foreach (DriveInfo drive in drives)
            {
                if (drive.DriveType == DriveType.Network)
                {
                    string localPath = drive.Name.TrimEnd('\\'); // 例如 "Z:"
                    string uncPath = GetUNCPath(localPath);
                    mappedDrives.Add(uncPath);
                }
            }
            string info = string.Empty;
            foreach (string drive in mappedDrives)
            {
                info += $"本地路径: {drive}\n";
            }
            MessageBox.Show(info);
        }

        /// <summary>
        /// 将本地映射路径转换为 UNC 路径
        /// </summary>
        public static string GetUNCPath(string mappedDrive)
        {
            StringBuilder uncPath = new StringBuilder(512);
            int bufferSize = uncPath.Capacity;

            int result = WNetGetConnection(mappedDrive, uncPath, ref bufferSize);
            if (result == 0)
            {
                return uncPath.ToString();
            }
            else
            {
                throw new Win32Exception(result, $"Failed to get UNC path. Error code: {result}");
            }
        }

        private void UploadButton_Click(object sender, MouseButtonEventArgs e)
        {
            string folderPath = @"\\886-9962057\d\TP-A356.2";
            if (!Directory.Exists(folderPath))
            {
                MessageBox.Show($"指定文件夹 {folderPath} 不存在！", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var openFileDialog = new Microsoft.Win32.OpenFileDialog
            {
               // InitialDirectory = folderPath,
                Filter = "Excel文件|*.xlsx",
                Title = "选择Excel文件",
                ValidateNames = true,
                CheckFileExists = true,
                Multiselect = true
            };
            openFileDialog.FileOk += (sender, e) =>
            {
                string selectedPath = Path.GetFullPath(openFileDialog.FileName);
                string targetFolder = Path.GetFullPath(folderPath);

                if (!selectedPath.StartsWith(targetFolder, StringComparison.OrdinalIgnoreCase))
                {
                    MessageBox.Show($"只能选择 {targetFolder} 内的文件！", "路径限制", MessageBoxButton.OK, MessageBoxImage.Warning);
                    e.Cancel = true;
                }
            };

            if (openFileDialog.ShowDialog() == true)
            {
                // 清除现有数据
                excelDataGrid.ItemsSource = null;
                var vm = DataContext as TPAutoUploadViewModel;
                if (vm != null)
                {
                    vm.PreviewData.Clear();
                }

                // 获取 ElementManagementViewModel 实例
                var elementManagementViewModel = (Application.Current as App)?.Container.Resolve<ElementManagementViewModel>();
                if (elementManagementViewModel != null)
                {
                    // 处理所有选中的文件
                    foreach (var filePath in openFileDialog.FileNames)
                    {
                        try
                        {
                            // 调用 AddBatchCommand 的处理逻辑
                            var element = elementManagementViewModel.ProcessExcelFileBatch(filePath);
                            using (var db = new SqlSugarHelper().GetInstance())
                            {
                                // 检查是否已存在
                                var existingElement = db.Queryable<Element>()
                                    .Where(it => it.Brand == element.Brand && it.Transfernumber == element.Transfernumber)
                                    .First();
                                
                                if (existingElement == null)
                                {
                                    // 插入新数据
                                    db.Insertable(element).ExecuteCommand();
                                    
                                    // 更新牌号列表
                                    var re = db.Queryable<BrandAndStoveNumber>().Select(it => it.Name).ToList();
                                    var Brandlist = new List<string> { element.Brand };
                                    List<BrandAndStoveNumber> listadd = new List<BrandAndStoveNumber>();
                                    foreach (var item in Brandlist)
                                    {
                                        if (re.Count > 0)
                                        {
                                            if (!re.Contains(item)) listadd.Add(new BrandAndStoveNumber() { Name = item, CreateTime = DateTime.Now, UpdateTime = DateTime.Now });
                                        }
                                        else
                                        {
                                            listadd.Add(new BrandAndStoveNumber() { Name = item, CreateTime = DateTime.Now, UpdateTime = DateTime.Now });
                                        }
                                    }
                                    if (listadd.Any())
                                    {
                                        db.Insertable(listadd).ExecuteCommand();
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            // 只记录错误，不显示消息框
                            System.Diagnostics.Debug.WriteLine($"处理文件失败：{ex.Message}");
                        }
                    }

                    // 重新加载数据
                    elementManagementViewModel.LoadElements();
                    elementManagementViewModel.UpdatePagedElements();
                }

                // 处理预览数据
                foreach (var filePath in openFileDialog.FileNames)
                {
                    ProcessExcelFile(filePath);
                }
            }
        }

        public void ProcessExcelFile(string filePath)
        {
            try
            {
                // 检查文件是否存在
                if (!File.Exists(filePath))
                {
                    throw new FileNotFoundException("找不到指定的文件。", filePath);
                }

                // 检查文件访问权限
                try
                {
                    using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // 如果能打开文件，说明有访问权限
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    throw new UnauthorizedAccessException("无法访问文件，请检查文件权限或以管理员身份运行程序。");
                }

                using (var package = new ExcelPackage(new FileInfo(filePath)))
                {
                    var workbook = package.Workbook;
                    if (workbook.Worksheets.Count == 0)
                    {
                        throw new Exception("Excel文件中没有工作表。");
                    }

                    var worksheet = workbook.Worksheets[0];
                    if (worksheet.Dimension == null)
                    {
                        throw new Exception("工作表是空的。");
                    }

                    var endRow = worksheet.Dimension.End.Row;
                    var endColumn = worksheet.Dimension.End.Column;

                    if (endRow < 2)
                    {
                        throw new Exception("Excel文件中数据行数不足。");
                    }

                    // 创建数据表来存储Excel数据
                    var dataTable = new System.Data.DataTable();
                    dataTable.TableName = Path.GetFileNameWithoutExtension(filePath);

                    // 添加文件名列
                    dataTable.Columns.Add("文件名", typeof(string));

                    // 添加列
                    for (int col = 1; col <= endColumn; col++)
                    {
                        var columnName = worksheet.Cells[1, col].Text.ToString();
                        if (string.IsNullOrEmpty(columnName))
                        {

                            columnName = $"Column {col}";
                        }
                        if (col == 1) columnName = "日期";
                        // 检查列名是否已存在
                        if (dataTable.Columns.Contains(columnName))
                        {
                            columnName = $"{columnName}_{col}";
                        }

                        dataTable.Columns.Add(columnName);
                    }

                    // 添加数据行
                    for (int row = 2; row <= endRow; row++)
                    {
                        var dataRow = dataTable.NewRow();
                        dataRow["文件名"] = Path.GetFileName(filePath);

                        for (int col = 1; col <= endColumn; col++)
                        {
                            dataRow[col] = worksheet.Cells[row, col].Text.ToString();
                        }
                        dataTable.Rows.Add(dataRow);
                    }

                    // 更新DataGrid
                    if (excelDataGrid.ItemsSource == null)
                    {
                        excelDataGrid.ItemsSource = dataTable.DefaultView;
                    }
                    else
                    {
                        // 合并多个数据表
                        var currentTable = (excelDataGrid.ItemsSource as DataView)?.Table;
                        if (currentTable != null)
                        {
                            foreach (DataRow row in dataTable.Rows)
                            {
                                currentTable.ImportRow(row);
                            }
                            excelDataGrid.ItemsSource = currentTable.DefaultView;
                        }
                    }

                    // 更新预览数据
                    var vm = DataContext as TPAutoUploadViewModel;
                    if (vm != null)
                    {
                        vm.UpdatePreviewData(dataTable);
                    }
                }
                statusText.Text = "上传完成";
                statusText.Foreground = new SolidColorBrush(Color.FromRgb(40, 167, 69));
            }
            catch (FileNotFoundException ex)
            {
                statusText.Text = "文件不存在: " + ex.Message;
                statusText.Foreground = new SolidColorBrush(Color.FromRgb(220, 53, 69));
            }
            catch (UnauthorizedAccessException ex)
            {
                statusText.Text = ex.Message;
                statusText.Foreground = new SolidColorBrush(Color.FromRgb(220, 53, 69));
                MessageBox.Show(ex.Message, "访问权限错误", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            catch (Exception ex)
            {
                statusText.Text = "上传失败: " + ex.Message;
                statusText.Foreground = new SolidColorBrush(Color.FromRgb(220, 53, 69));
            }
        }

        // 添加拖拽相关事件
        private void Grid_DragEnter(object sender, DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                    if (files.Length > 0)
                    {
                        string filePath = files[0];
                        if (Path.GetExtension(filePath).ToLower() == ".xlsx")
                        {
                            // 检查文件访问权限
                            try
                            {
                                using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                                {
                                    e.Effects = DragDropEffects.Copy;
                                    dropOverlay.Visibility = Visibility.Visible;
                                    dropOverlay.Opacity = 1;
                                }
                            }
                            catch (UnauthorizedAccessException)
                            {
                                e.Effects = DragDropEffects.None;
                                statusText.Text = "无法访问文件，请检查文件权限或以管理员身份运行程序。";
                                statusText.Foreground = new SolidColorBrush(Color.FromRgb(220, 53, 69));
                            }
                        }
                        else
                        {
                            e.Effects = DragDropEffects.None;
                            statusText.Text = "请拖放Excel文件（.xlsx格式）";
                            statusText.Foreground = new SolidColorBrush(Color.FromRgb(220, 53, 69));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                e.Effects = DragDropEffects.None;
                statusText.Text = "拖放错误: " + ex.Message;
                statusText.Foreground = new SolidColorBrush(Color.FromRgb(220, 53, 69));
            }
            e.Handled = true;
        }

        private void Grid_DragLeave(object sender, DragEventArgs e)
        {
            dropOverlay.Visibility = Visibility.Collapsed;
            dropOverlay.Opacity = 0;
            e.Handled = true;
        }

        // 修改现有的Drop事件
        private void Grid_Drop(object sender, DragEventArgs e)
        {
            dropOverlay.Visibility = Visibility.Collapsed;
            dropOverlay.Opacity = 0;

            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (files.Length > 0 && Path.GetExtension(files[0]).ToLower() == ".xlsx")
                {
                    ProcessExcelFile(files[0]);
                }
                else
                {
                    statusText.Text = "请拖放一个Excel文件";
                    statusText.Foreground = new SolidColorBrush(Color.FromRgb(220, 53, 69));
                }
            }
        }

        private void ClearData_Click(object sender, RoutedEventArgs e)
        {
            // 清除DataGrid数据
            excelDataGrid.ItemsSource = null;

            // 清除预览数据
            var vm = DataContext as TPAutoUploadViewModel;
            if (vm != null)
            {
                vm.PreviewData.Clear();
            }

            // 重置状态文本
            statusText.Text = "";
        }

        // 拖拽相关事件处理
        private Point _dragStartPoint;
        private bool _isDragging = false;
        private object _draggedItem = null;

        private void PreviewDataList_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var listBox = sender as ListBox;
            var item = GetItemAtPoint(listBox, e.GetPosition(listBox));
            
            if (item != null)
            {
                var previewItem = item as ViewModels.TPAutoUploadViewModel.PreviewDataItem;
                if (previewItem != null && previewItem.CanDrag)
                {
                    _dragStartPoint = e.GetPosition(listBox);
                    _draggedItem = item;
                    _isDragging = false;
                }
            }
        }

        private void PreviewDataList_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (_draggedItem != null && e.LeftButton == MouseButtonState.Pressed)
            {
                var listBox = sender as ListBox;
                var currentPoint = e.GetPosition(listBox);
                
                if (!_isDragging && 
                    Math.Abs(currentPoint.X - _dragStartPoint.X) > SystemParameters.MinimumHorizontalDragDistance ||
                    Math.Abs(currentPoint.Y - _dragStartPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
                {
                    _isDragging = true;
                    DragDrop.DoDragDrop(listBox, _draggedItem, DragDropEffects.Move);
                }
            }
        }

        private void PreviewDataList_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(ViewModels.TPAutoUploadViewModel.PreviewDataItem)))
            {
                e.Effects = DragDropEffects.Move;
                
                var listBox = sender as ListBox;
                var targetItem = GetItemAtPoint(listBox, e.GetPosition(listBox));
                
                if (targetItem != null)
                {
                    var previewItem = targetItem as ViewModels.TPAutoUploadViewModel.PreviewDataItem;
                    if (previewItem != null)
                    {
                        previewItem.IsDragOver = true;
                    }
                }
            }
            else
            {
                e.Effects = DragDropEffects.None;
            }
            e.Handled = true;
        }

        private void PreviewDataList_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(ViewModels.TPAutoUploadViewModel.PreviewDataItem)))
            {
                var listBox = sender as ListBox;
                var draggedItem = e.Data.GetData(typeof(ViewModels.TPAutoUploadViewModel.PreviewDataItem)) as ViewModels.TPAutoUploadViewModel.PreviewDataItem;
                var targetItem = GetItemAtPoint(listBox, e.GetPosition(listBox)) as ViewModels.TPAutoUploadViewModel.PreviewDataItem;
                
                if (draggedItem != null && targetItem != null && draggedItem != targetItem)
                {
                    var vm = DataContext as TPAutoUploadViewModel;
                    if (vm != null)
                    {
                        int fromIndex = vm.PreviewData.IndexOf(draggedItem);
                        int toIndex = vm.PreviewData.IndexOf(targetItem);
                        vm.MoveItem(fromIndex, toIndex);
                        
                        // 清除拖拽状态
                        foreach (var item in vm.PreviewData)
                        {
                            item.IsDragOver = false;
                        }
                    }
                }
            }
            
            _isDragging = false;
            _draggedItem = null;
            e.Handled = true;
        }

        private object GetItemAtPoint(ListBox listBox, Point point)
        {
            var element = listBox.InputHitTest(point) as DependencyObject;
            while (element != null && !(element is ListBoxItem))
            {
                element = VisualTreeHelper.GetParent(element);
            }
            
            if (element is ListBoxItem listBoxItem)
            {
                return listBox.ItemContainerGenerator.ItemFromContainer(listBoxItem);
            }
            
            return null;
        }


    }
}
